﻿using Kinlo.Entitys;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.Devices.Models;
using XingLucifer.IBase;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.ST5520)]
    public class ST5520Handle : ServierBase
    {
        public ST5520Handle(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig, UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic) : 
            base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {

        }
        private volatile int _ngShortCircuit = 0;
        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                _ngShortCircuit = 0;
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_Kurzschluss, context.AddressingMethod);
                if (erinnerungen.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");
                Parallel.ForEach(erinnerungen.Item2, battery =>
                {
                    Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
                    && x.DeviceType == context.DeviceType && x.Index == battery.Index);
                    if (device == null)
                    {
                        RunLog($"找不到[{battery.Index}]号设备", MessageLevelType.错误);
                        return;
                    }
                    ST5520ResultModel st5520_result = null;
                    try
                    {
                        st5520_result = device.Communication.ReadClass<ST5520ResultModel>(0);
                    }
                    catch (Exception ex)
                    {
                        $"-[{battery.Index}] 获取结果时发生异常：{ex}".RunLog(MessageLevelType.警告);
                    }
                    if (battery.SnowflakeId == -1)
                    {
                        RunLog($"-[{battery.Index}] 短路测试仪点检");
                        WriteResult("",st5520_result == null ? ResultTypes.不合格 : ResultTypes.合格, plc, battery.Address_Struct, context);
                        return;
                    }
                    if (st5520_result == null)
                    {
                        $"-[{battery.Index}] 采集数据异常".RunLog(MessageLevelType.警告);
                        WriteResult("",ResultTypes.不合格, plc, battery.Address_Struct, context);
                        return;
                    }
                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId, DBSuffix);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                        WriteResult("",ResultTypes.数据库找不到电池, plc, battery.Address_Struct, context);
                        return;
                    }
                    RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}]");
                    //switch (battery.Data_PLC)
                    //{
                    //    case 1:
                    //        entity.TimeElectrodes = dateTime.GetJSTimeUtc();
                    //        entity.ElectrodesTestValue = st5520_result.Test_Value;
                    //        entity.ResultElectrodes = st5520_result.Test_Result == "" ? ResultTypes.Hi_Pot阻值NG : ResultTypes.合格;
                    //        if (entity.ResultElectrodes != ResultTypes.合格 && entity.ResultTotal == ResultTypes._)
                    //        {
                    //            entity.ResultTotal = entity.ResultElectrodes;
                    //            Interlocked.Increment(ref _ngShortCircuit);
                    //        }
                    //        if (entity.ResultTotal == ResultTypes._ && !RangeCheck(entity.ElectrodesTestValue, entity.RangeElectrodes))
                    //        {
                    //            entity.ResultTotal = ResultTypes.电极超范围;
                    //            Interlocked.Increment(ref _ngShortCircuit);
                    //        }
                    //        break;
                    //    case 2:
                    //        entity.TimeHousing = dateTime.GetJSTimeUtc();
                    //        entity.ResistanceTestValue = st5520_result.Test_Value;
                    //        entity.ResultHousing = st5520_result.Test_Result == "" ? ResultTypes.Hi_Pot阻值NG : ResultTypes.合格;
                    //        if (entity.ResultHousing != ResultTypes.合格 && entity.ResultTotal == ResultTypes._)
                    //        {
                    //            entity.ResultTotal = entity.ResultHousing;
                    //            Interlocked.Increment(ref _ngShortCircuit);
                    //        }
                    //        if (entity.ResultTotal == ResultTypes._ && !RangeCheck(entity.ResistanceTestValue, entity.RangeHousing))
                    //        {
                    //            entity.ResultTotal = ResultTypes.壳体超范围;
                    //            Interlocked.Increment(ref _ngShortCircuit);
                    //        }
                    //        break;
                    //}
                    //try
                    //{
                    //    _homeStatic.AddShortCircuitBattery(entity.BarCode, entity);
                    //    entity.Update();
                    //}
                    //catch (Exception ex)
                    //{
                    //    RunLog($"-[{battery.Index}] [{(battery.Data_PLC == 1 ? "电极" : "壳体")}] 更新数据异常：{ex}");
                    //}
                    WriteResult(entity.BarCode,entity.ResultTotal != ResultTypes._ ? entity.ResultTotal : ResultTypes.合格, plc, battery.Address_Struct, context);
                });
                _homeStatic.ChartData.NG_ShortCircuit += _ngShortCircuit;
            }
            catch (Exception ex)
            {

            }
            
            return base.Handle(context);
        }

        private bool RangeCheck(double value, string range)
        {
            string[] str = range.Split('-');
            double up = double.Parse(str[0]);
            double down = double.Parse(str[1]);
            return value <= up && value >= down;
        }
    }
}
